import api from "../../utils/api";
import { PAGE_SIZE, START_Y_IMG, START_D_IMG } from "../../constant/index";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1, // 当前页
    totalPage: 1, // 总页数
    loading: true,
    pageErrorType: "",
    pageFooterType: "",
    list: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getCommmentData();
  },

  getCommmentData() {
    api.userComment({
      data: {
        pageNum: this.data.pageNum,
        pageSize: PAGE_SIZE,
      },
      success: (res) => {
        const { code, data = {} } = res || {};
        if (+code === 0) {
          const { dataList, totalPage } = data;
          const { list } = this.data;
          const newData = this.dataAdaptar(dataList || []);
          this.setData({
            list: [...list, ...newData],
            totalPage,
            pageFooterType:
              this.data.pageNum === 1 && data.total <= 10 ? "end" : "", // 数据只够一页展示end
          });
          this.handlePageError("");
        } else {
          this.handlePageError("error");
        }
      },
      fail: (res) => {
        this.handlePageError("error");
      },
    });
  },

  dataAdaptar(list = []) {
    return list.map((item, index) => {
      const star = [];
      const [createDate = ""] = item.createDate.split(" "); // 截取日期
      const imgList =
        Array.isArray(item.imgList) && item.imgList.map((item) => item.file);
      for (let i = 0; i < 5; i++) {
        star.push(i < item.star ? START_Y_IMG : START_D_IMG);
      }
      return {
        star,
        imgList,
        createDate,
        id: index,
        content: item.content || "",
        userHead: item.userHead || "",
        nickname: item.nickname || "",
        productName: item.productName || "",
      };
    });
  },

  /**
   * @description: 处理页面异常
   */
  handlePageError(type) {
    this.setData({
      pageErrorType: type,
      loading: false,
    });
  },

  onRetry() {
    this.setData(
      {
        pageFooterType: "ing",
        loading: true,
      },
      () => {
        this.getCommmentData();
      }
    );
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { pageNum, totalPage } = this.data;
    if (pageNum >= totalPage) {
      this.setData({
        pageFooterType: "end",
      });
    } else {
      this.setData(
        {
          pageNum: pageNum + 1,
          pageFooterType: "ing",
        },
        () => {
          this.getCommmentData();
        }
      );
    }
  },

  /**
   * @description: 预览图片
   * @param {*} e
   */
  previewImage(e) {
    const { index, item } = e.currentTarget.dataset || {};
    wx.previewImage({
      current: index,
      urls: item,
    });
  },
});
